import Taro from '@tarojs/taro-rn';
import * as tslib_1 from "tslib";
import React from 'react';
import { Component } from "@tarojs/taro-rn";
import { View, Text, Image, RichText } from "@tarojs/components-rn";
import { getRuntime, subtime, ServerHost, htmlToText } from "../../utils/common";
// import {WxShare} from '../../utils/shareH5Server';
import { toJS } from "mobx";
import { inject, observer } from "@tarojs/mobx-rn";
import detailStyleSheet from "./detail_styles";
import iconCollection from '../../assets/img/icon_03.png';
import iconCollection_on from '../../assets/img/icon_03_on.png';
import iconShare from '../../assets/img/icon_04.png';
import share_icon from "../../assets/img/share_arrow.png";
import close_icon from "../../assets/img/icon_close_bold.png";
var _styleSheet = detailStyleSheet;

function _getClassName() {
  var className = [];
  var args = arguments[0];
  var type = Object.prototype.toString.call(args).slice(8, -1).toLowerCase();

  if (type === 'string') {
    args = args.trim();
    args && className.push(args);
  } else if (type === 'array') {
    args.forEach(function (cls) {
      cls = _getClassName(cls).trim();
      cls && className.push(cls);
    });
  } else if (type === 'object') {
    for (var k in args) {
      k = k.trim();

      if (k && args.hasOwnProperty(k) && args[k]) {
        className.push(k);
      }
    }
  }

  return className.join(' ').trim();
}

function _getStyle(classNameExpression) {
  var className = _getClassName(classNameExpression);

  var classNameArr = className.split(/\s+/);
  var style = [];

  if (classNameArr.length === 1) {
    style.push(_styleSheet[classNameArr[0].trim()]);
  } else {
    classNameArr.forEach(function (cls) {
      style.push(_styleSheet[cls.trim()]);
    });
  }

  return style;
}

let Detail = class Detail extends Component {
  constructor(props) {
    super(props);

    this.getJsApiParam = () => {
      let currentUrl = window.location.href;
      let apiUrl = `${ServerHost}/api/Account/getWxJsApiParams?curUrl=${currentUrl}`;
      Taro.showLoading({ title: '加载中...' });
      fetch(apiUrl, {
        method: 'GET',
        mode: "cors",
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        credentials: 'same-origin'
      }).then(response => {
        Taro.hideLoading();
        return response.json();
      }).then(response => {
        let appId = response.appId;
        let timestamp = response.timestamp;
        let nonceStr = response.nonceStr;
        let signature = response.signature;
        this.setState({ wxConfig: response });
        wx.config({
          debug: false,
          appId: appId,
          timestamp: timestamp,
          nonceStr: nonceStr,
          signature: signature,
          // jsApiList: ['updateAppMessageShareData','onMenuShareAppMessage'], // 必填，需要使用的JS接口列表
          jsApiList: 'updateAppMessageShareData,onMenuShareTimeline,onMenuShareAppMessage,onMenuShareQQ,onMenuShareWeibo'.split(',')
        });
      }).catch(error => {
        console.log(error);
      });
    };

    this.state = {
      item: {},
      isCollection: false,
      isTips: false,
      tipsText: '',
      wxConfig: {},
      isShare: false
    };
    // 配置微信分享
  }
  componentWillMount() {
    Taro.setNavigationBarTitle({ title: '动态详情' });
    this.getJsApiParam();
    this.getDynamicInfo(this.$router.params.id);
    let isCollection = parseInt(this.$router.params.isCollection);
    if (isCollection === 1) {
      this.setState({ isCollection: true });
    }
  }
  toggleCollection() {
    if (!getRuntime().getToken()) {
      getRuntime().navigateTo('/pages/login/login');
      return;
    }
    let { userStore } = this.props.stores;
    this.setState({
      isCollection: !this.state.isCollection
    }, () => {
      if (this.state.isCollection) {
        // 收藏
        userStore.saveUserCollection({
          form: {
            dynamicsId: parseInt(this.$router.params.id),
            userCollectionType: 0
          },
          callback: () => {
            this.setState({ isTips: true, tipsText: '收藏成功~' });
          }
        });
      } else {
        // 取消收藏
        userStore.cancelUserCollection({
          form: {
            id: parseInt(this.$router.params.id),
            userCollectionType: 0
          },
          callback: () => {
            this.setState({ isTips: true, tipsText: '取消收藏成功~' });
          }
        });
      }
    });
  }
  getDynamicInfo(id) {
    let dynamicStore = this.props.stores.DynamicStore;
    dynamicStore.getDynamicInfo({
      id,
      callback: res => {
        // console.log(res)
        let isCollection = parseInt(this.$router.params.isCollection) === 1 ? true : toJS(res.isCollection);
        this.setState({
          item: toJS(res),
          isCollection
        }, () => {
          this.share();
        });
      }
    });
  }
  handelRouter(url = '/pages/index/index') {
    getRuntime().navigateTo(url);
  }
  share() {
    // if(!getRuntime().getToken()) { getRuntime().navigateTo('/pages/login/login'); return }
    let { item } = this.state;
    let url1 = ServerHost + '/m/#/pages/dynamic/detail?id=' + item.id;
    let title = item.title;
    let desc = htmlToText(item.content);
    let imgUrl = item.logo;
    // wxShare(title, desc,url1,imgUrl)
    var shareData = {
      title,
      desc,
      imgUrl,
      otherImgUrl: '',
      url: window.location.href,
      link: window.location.href
    };
    wx.ready(function () {
      wx.onMenuShareTimeline(shareData);
      wx.updateAppMessageShareData(shareData);
      wx.onMenuShareQQ(shareData);
      wx.onMenuShareWeibo(shareData);
    });
    // WxShare(url,item.logo,item.title,partOf(item.content, 30))
  }
  btnShare() {
    this.setState({ isShare: true });
  }
  onClose() {
    this.setState({ isShare: false });
  }
  componentDidHide() {
    this.setState({ isShare: false });
  }
  render() {
    let { item, isCollection, isShare } = this.state;
    return <View style={[_styleSheet["article-wrap"], _styleSheet["dynamic-article"]]}>
       <View style={_styleSheet["article-info"]}>
         <View style={_styleSheet["title"]}>
           {item.title}
         </View>
         <Text style={_styleSheet["source"]}>{item.author}</Text>
         <Text style={_styleSheet["date"]}>{subtime(item.creationTime)}</Text>
       </View>
        <View style={[_styleSheet["article"], _styleSheet["rich-text"]]}>
          <RichText nodes={item.content} />
        </View>

        <View style={_styleSheet["footer-block"]} />
        <View style={_styleSheet["footer"]}>
          <View style={_styleSheet["read-count"]}>{item.readAmount}次浏览</View>
          <View style={_styleSheet["share"]}>
            <View onClick={this.toggleCollection.bind(this)} style={_styleSheet["collection"]}>
              {!isCollection && <View>
                   <Image src={iconCollection} style={_styleSheet["collection-img"]} />
                   <Text>收藏</Text>
                </View>}
              {isCollection && <View>
                   <Image src={iconCollection_on} style={_styleSheet["collection-img"]} />
                   <Text>已收藏</Text>
                </View>}
            </View>
            <View onClick={this.btnShare.bind(this)} style={_styleSheet["collection"]}>
              <Image src={iconShare} style={_styleSheet["share-img"]} />
              分享
            </View>
          </View>
        </View>
        <View style={_styleSheet["footer-block"]} />
        <View style={_styleSheet["footer-block"]} />
        <View style={_getStyle(isShare ? 'share-arrow share-arrow-active' : 'share-arrow')}>
          <Image src={share_icon} style={_styleSheet["share-arrow-icon"]} />
          <View style={_styleSheet["con"]}>
            <View>请点击右上角</View>
            <View>通过【发送给朋友】</View>
            <View>分享给好友</View>
          </View>
          <Image onClick={this.onClose.bind(this)} src={close_icon} style={_styleSheet["close-icon"]} />
        </View>
      </View>;
  }
};
Detail = tslib_1.__decorate([inject("stores"), observer], Detail);
export default Detail;